package yc.bluetooth.ycvoiceprotest;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bluetoothlibrary.broadcastreceiver.BluetoothBroadcastReceiver;

import yc.bluetooth.libvoice.VoiceTool;
import yc.bluetooth.libvoice.VoiceToolListener;
import yc.bluetooth.libvoice.util.HandlerUtil;
import yc.bluetooth.libvoice.util.TimeUtil;
import yc.bluetooth.ycvoiceprotest.base.BaseActivity;
import yc.bluetooth.ycvoiceprotest.constant.Cons;
import yc.bluetooth.ycvoiceprotest.data.BDevice;
import yc.bluetooth.ycvoiceprotest.pop.PopSearchDevice;

/**
 * 金桔遥控器
 */
public class KeyVoiceJinActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "KeyVoiceJin";

    public static final int KEY_CUSTOMIZE = 1;
    public static final int KEY_OFF = 2;
    public static final int KEY_SILENT = 3;
    public static final int KEY_SETTING = 4;
    public static final int KEY_UP = 5;
    public static final int KEY_LEFT = 6;
    public static final int KEY_RIGHT = 7;
    public static final int KEY_DOWN = 8;
    public static final int KEY_OK = 9;
    public static final int KEY_MENU = 10;
    public static final int KEY_BACK= 11;
    public static final int KEY_VOICE = 12;
    public static final int KEY_P_ADD = 13;
    public static final int KEY_P_MINUS = 14;
    public static final int KEY_HOME = 15;
    public static final int KEY_V_ADD = 16;
    public static final int KEY_V_MINUS = 17;

    private TextView tvSearch;
    private ImageView ivConState;
    private TextView tvName;
    private TextView tvAddress;
    private Button btConDisCon;
    private Button btClearLog;
    private ScrollView svLogInfo;
    private LinearLayout tvLogInfo;
    private ProgressBar pbLoading;

    private Button btBack;  //返回键
    private RelativeLayout rlOff;        //关
    private RelativeLayout rlHome;       //主页
    private RelativeLayout rlMenu;       //菜单
    private RelativeLayout rlUp;         //上
    private RelativeLayout rlLeft;       //左
    private RelativeLayout rlOk;         //确认
    private RelativeLayout rlRight;      //右
    private RelativeLayout rlDown;       //下
    private RelativeLayout rlEnterMouseMode; //进入鼠标模式
    private RelativeLayout rlBack;       //返回
    private RelativeLayout rlVoice;      //语音
    private RelativeLayout rlVAdd;       //语音加
    private RelativeLayout rlVMinus;     //语音减
    private RelativeLayout rlSilent;     //静音
    private RelativeLayout rlPGUp;       //PG 上
    private RelativeLayout rlPGDown;     //PG 下

    private VoiceTool voiceTool;
    private PopSearchDevice popSearchDevice;
    private BluetoothDevice curConDevice;
    private boolean curConState;

    //监听遥控器按键
    private MyKeyBroadcastReceiver myKeyBroadcastReceiver;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch(msg.what){
                case Cons.HANDLER_FOUND_DEVICE:
                    BDevice bDevice = (BDevice) msg.obj;
                    if(popSearchDevice != null){
                        popSearchDevice.addListItem(bDevice);
                    }
                    break;

                case Cons.HANDLER_SCAN_FINISH:
                case Cons.HANDLER_SCAN_OUT_TIME:
                    if(popSearchDevice != null){
                        popSearchDevice.hideProgress();
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_key_voice_jin;
    }

    @Override
    protected void initView() {
        tvSearch = findViewById(R.id.tv_search);
        ivConState = findViewById(R.id.iv_con_state);
        tvName = findViewById(R.id.tv_name);
        tvAddress = findViewById(R.id.tv_address);
        btConDisCon = findViewById(R.id.bt_con_dis_con);
        btClearLog = findViewById(R.id.bt_clear_log);
        svLogInfo = findViewById(R.id.sv_log_content);
        tvLogInfo = findViewById(R.id.tv_log_content);
        pbLoading = findViewById(R.id.pb_loading);

        btBack = findViewById(R.id.bt_back);
        rlOff = findViewById(R.id.rl_off);
        rlUp = findViewById(R.id.rl_up);
        rlLeft = findViewById(R.id.rl_left);
        rlOk = findViewById(R.id.rl_ok);
        rlRight = findViewById(R.id.rl_right);
        rlDown = findViewById(R.id.rl_down);
        rlMenu = findViewById(R.id.rl_menu);
        rlBack = findViewById(R.id.rl_back);
        rlVoice = findViewById(R.id.rl_voice);
        rlHome = findViewById(R.id.rl_home);
        rlVAdd = findViewById(R.id.rl_volume_add);
        rlVMinus = findViewById(R.id.rl_volume_minus);

        rlEnterMouseMode = findViewById(R.id.rl_enter_mouse_mode); //进入鼠标模式
        rlSilent = findViewById(R.id.rl_silent);     //静音
        rlPGUp = findViewById(R.id.rl_pg_up);       //PG 上
        rlPGDown = findViewById(R.id.rl_pg_down);     //PG 下
    }

    @Override
    protected void initListener() {
        tvSearch.setOnClickListener(this);
        btConDisCon.setOnClickListener(this);
        btClearLog.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        initBroadcastReceiver();
        voiceTool = new VoiceTool(KeyVoiceJinActivity.this);
        voiceTool.setListener(new VoiceToolListener() {
            @Override
            public void foundDevice(final BluetoothDevice bluetoothDevice, final int i, final byte[] bytes) {
                HandlerUtil.sendMsg(mHandler, Cons.HANDLER_FOUND_DEVICE,new BDevice(bluetoothDevice,i,bytes));
            }

            @Override
            public void scanFinished() {
                HandlerUtil.sendEmptyMsg(mHandler,Cons.HANDLER_SCAN_FINISH);
            }

            @Override
            public void scanOutTime() {
                HandlerUtil.sendEmptyMsg(mHandler,Cons.HANDLER_SCAN_OUT_TIME);
            }

            @Override
            public void pairConnectState(final boolean isConnected) {
                curConState = isConnected;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showConnectState(isConnected);
                    }
                });
            }

            @Override
            public void onUiStringNotify(final String s, final int i) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showLogInfo(s,i);
                    }
                });
            }

            @Override
            public void onSuccess() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showLogInfo("解码成功",1);
                    }
                });
            }

            @Override
            public void onError(final String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showLogInfo(s,2);
                    }
                });
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch(v.getId()) {
            case R.id.tv_search:  //搜索
                //先判断定位是否已开启
                if(!isLocationEnabled()){
                    Toast.makeText(KeyVoiceJinActivity.this, "请先打开定位服务", Toast.LENGTH_SHORT).show();
                    return;
                }

                if(popSearchDevice == null){
                    popSearchDevice = new PopSearchDevice(KeyVoiceJinActivity.this);
                }
                popSearchDevice.showPop();
                popSearchDevice.setPopListener(new PopSearchDevice.PopListener() {
                    @Override
                    public void onClickItem(BDevice bDevice) {
                        if(voiceTool != null){
                            //停止扫描
                            voiceTool.stopScanDevice();
                            //UI显示，配对连接设备
                            showDeviceInfo(bDevice);
                            voiceTool.pairConnectDevice(bDevice.bluetoothDevice);
                        }
                    }

                    @Override
                    public void onClosePop() {
                        //停止扫描
                        if(voiceTool != null){
                            voiceTool.stopScanDevice();
                        }
                        popSearchDevice = null;
                    }
                });
                //开启扫描
                if(voiceTool != null){
                    voiceTool.scanDevice();
                }
                break;

            case R.id.bt_con_dis_con:  //断开
                if(isEnter){
                    return;   //不响应OK键
                }

                if(curConState){  //断开连接
                    voiceTool.disPairDisConnectDevice();
                }

                break;


            case R.id.bt_clear_log:  //清空log
                if(isEnter){
                    return;   //不响应OK键
                }
                //清空log，清空进度条
                tvLogInfo.removeAllViews();
                break;
        }

    }

    /**
     * 自定义广播监听锁屏、开屏、解锁、Home键
     */
    class MyKeyBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            assert action != null;
            if(action.equals(Intent.ACTION_SCREEN_OFF)){  //锁屏
                //对于锁屏操作，由于先走的activity的onPause，onStop，
                // 所以不可以像以往反注册广播样在onPause里进行反注册，否则的话会接收不到锁屏操作
                Log.d(TAG, "锁屏键");
                setKeyBg(KEY_OFF);  //按键测试-主页

            }else if(action.equals(Intent.ACTION_SCREEN_ON)){  //开屏
                Log.d(TAG, "开屏键");
                setKeyBg(KEY_OFF);  //按键测试-主页

            }else if(action.equals(Intent.ACTION_USER_PRESENT)){ //解锁
                Log.d(TAG, "解锁键");

            }else if(action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)){ //Home键
                Log.d(TAG, "Home键");

            }
        }
    }

    private void initBroadcastReceiver() {

        myKeyBroadcastReceiver = new MyKeyBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);  //开屏
        filter.addAction(Intent.ACTION_SCREEN_OFF); //锁屏
        filter.addAction(Intent.ACTION_USER_PRESENT); //解锁
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);//Home键
        registerReceiver(myKeyBroadcastReceiver,filter);
    }

    /**
     * 设置所有控件背景初始化
     */
    private void setAllKeyInit(){
        rlOff.setBackgroundResource(R.drawable.bg_round);
        rlUp.setBackgroundResource(R.drawable.bg_rectangle);
        rlLeft.setBackgroundResource(R.drawable.bg_rectangle);
        rlOk.setBackgroundResource(R.drawable.bg_round_ok);
        rlRight.setBackgroundResource(R.drawable.bg_rectangle);
        rlDown.setBackgroundResource(R.drawable.bg_rectangle);
        rlMenu.setBackgroundResource(R.drawable.bg_oval);
        rlBack.setBackgroundResource(R.drawable.bg_oval);
        rlVoice.setBackgroundResource(R.drawable.bg_round);
        rlHome.setBackgroundResource(R.drawable.bg_round);
        rlVAdd.setBackgroundResource(R.drawable.bg_rectangle);
        rlVMinus.setBackgroundResource(R.drawable.bg_rectangle);
    }

    /**
     * 设置按键背景
     * @param  keyType 1~17
     */
    public void setKeyBg(int keyType){
        //先初始化所有控件
        setAllKeyInit();

        if(keyType == KEY_CUSTOMIZE){  //自定义

        }else if(keyType == KEY_OFF){ //关机
            rlOff.setBackgroundResource(R.drawable.bg_round_green);
        }else if(keyType == KEY_SILENT) { //静音

        }else if(keyType == KEY_SETTING) { //设置

        }else if(keyType == KEY_UP) { //上
            rlUp.setBackgroundResource(R.drawable.bg_rectangle_green);
        }else if(keyType == KEY_LEFT) { //左
            rlLeft.setBackgroundResource(R.drawable.bg_rectangle_green);
        }else if(keyType == KEY_RIGHT) { //右
            rlRight.setBackgroundResource(R.drawable.bg_rectangle_green);
        }else if(keyType == KEY_DOWN) { //下
            rlDown.setBackgroundResource(R.drawable.bg_rectangle_green);
        }else if(keyType == KEY_OK) { //OK
            rlOk.setBackgroundResource(R.drawable.bg_round_ok_green);
        }else if(keyType == KEY_MENU) { //菜单
            rlMenu.setBackgroundResource(R.drawable.bg_oval_green);
        }else if(keyType == KEY_BACK) { //返回
            rlBack.setBackgroundResource(R.drawable.bg_oval_green);
        }else if(keyType == KEY_VOICE){ //语音
            rlVoice.setBackgroundResource(R.drawable.bg_round_green);
        }else if(keyType == KEY_HOME){ //主页
            rlHome.setBackgroundResource(R.drawable.bg_round_green);
        }else if(keyType == KEY_P_ADD) { //p+

        }else if(keyType == KEY_P_MINUS) { //p-

        }else if(keyType == KEY_V_ADD) { //v+
            rlVAdd.setBackgroundResource(R.drawable.bg_rectangle_green);
        }else if(keyType == KEY_V_MINUS) { //v-
            rlVMinus.setBackgroundResource(R.drawable.bg_rectangle_green);
        }

    }

    private boolean isEnter = false;  //遥控器是否点击OK键

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        Log.i(TAG,"dispatchKeyEvent event:"+event);
        showLogInfo("按键："+ event,0);
        int keyCode = event.getKeyCode();

        isEnter = false;  //除了点击OK键该值为true,其它按键该值均为false
        if (keyCode == KeyEvent.KEYCODE_F4) { //3D/自定义键
            Log.i(TAG,"遥控器按键：自定义");
            setKeyBg(KEY_CUSTOMIZE);
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_MUTE) { //静音
            Log.i(TAG,"遥控器按键：静音");
            setKeyBg(KEY_SILENT);
        } else if (keyCode == KeyEvent.KEYCODE_F6) { //设置
            Log.i(TAG,"遥控器按键：设置");
            setKeyBg(KEY_SETTING);
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP) { //上
            Log.i(TAG,"遥控器按键：上");
            setKeyBg(KEY_UP);
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { //左
            Log.i(TAG,"遥控器按键：左");
            setKeyBg(KEY_LEFT);
        } else if (keyCode == KeyEvent.KEYCODE_ENTER) { //确认
            isEnter = true;   //不让界面按钮控件响应
            Log.i(TAG,"遥控器按键：确认");
            setKeyBg(KEY_OK);
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { //右
            Log.i(TAG,"遥控器按键：右");
            setKeyBg(KEY_RIGHT);
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { //下
            Log.i(TAG,"遥控器按键：下");
            setKeyBg(KEY_DOWN);
        } else if (keyCode == KeyEvent.KEYCODE_MENU) { //option/菜单
            Log.i(TAG,"遥控器按键：菜单");
            setKeyBg(KEY_MENU);
        } else if (keyCode == KeyEvent.KEYCODE_BACK) { //返回
            // TODO: 2019/10/22 注意：点击了 返回键，就要断开与遥控器的连接
            Log.i(TAG,"遥控器按键：返回");
            setKeyBg(KEY_BACK);   //return true;拦截事件传递,从而屏蔽back键。
            return true;   //此处return true使系统返回键不响应！！！且重写onBackPressed()中取消系统相应。

        } else if (keyCode == KeyEvent.KEYCODE_F1) { //f+ 频道+
            Log.i(TAG,"遥控器按键：P+");
            setKeyBg(KEY_P_ADD);
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) { //v+ 语音+
            Log.i(TAG,"遥控器按键：V+");
            setKeyBg(KEY_V_ADD);
        } else if (keyCode == KeyEvent.KEYCODE_MOVE_HOME) { //主页
            Log.i(TAG,"遥控器按键：主页");
            setKeyBg(KEY_HOME);
            return true;  //return true;拦截事件传递,从而屏蔽Home键。
        } else if (keyCode == KeyEvent.KEYCODE_HOME) { //主页
            Log.i(TAG,"遥控器按键：主页KEYCODE_HOME");
            setKeyBg(KEY_HOME);
            return true;  //return true;拦截事件传递,从而屏蔽Home键。
        } else if (keyCode == KeyEvent.KEYCODE_F3) { //P- 频道-
            Log.i(TAG,"遥控器按键：P-");
            setKeyBg(KEY_P_MINUS);
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) { //v- 语音-
            Log.i(TAG,"遥控器按键：V-");
            setKeyBg(KEY_V_MINUS);
        }

        return super.dispatchKeyEvent(event);
    }

    @Override
    public void onBackPressed() {
        Log.d(TAG, "onBackPressed()");
//        super.onBackPressed();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d(TAG, "onKeyDown()");
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 展示已选中的蓝牙设备
     * @param bDevice
     */
    @SuppressLint("SetTextI18n")
    public void showDeviceInfo(BDevice bDevice){
        curConDevice = bDevice.bluetoothDevice;
        if (curConDevice.getName() != null) {
            tvName.setText(curConDevice.getName());
        } else {
            tvName.setText("NULL");
        }

        tvAddress.setText(curConDevice.getAddress());
    }

    /**
     * 显示当前连接状态
     */
    private void showConnectState(boolean isConnected) {
        if (!isConnected) {  //未连接
            Log.d(TAG, "更新断开状态");
            btConDisCon.setText("连接");
            btConDisCon.setBackgroundResource(R.drawable.bg_bt_oval_grey);
            ivConState.setImageResource(R.drawable.ic_bt_disconnected_64);

        } else {  //已连接
            Log.d(TAG, "更新连接状态");
            btConDisCon.setText("断开");
            btConDisCon.setBackgroundResource(R.drawable.bg_bt_oval);
            ivConState.setImageResource(R.drawable.ic_bt_connected_64);

        }
    }

    /**
     * 显示Log信息，0--文本显示黑色(正常log) 1--文本显示绿色(成功)  2--文本显示红色(失败)
     */
    public void showLogInfo(String message, int type) {

        String realMsg = "";
        TextView tv = new TextView(this);
        tv.setTextSize(8);
        if(message.equals("\n")){
            tv.setText("\n");
        }else{
            realMsg = TimeUtil.timeToFormatNoYear(System.currentTimeMillis())+"     "+message;
            tv.setText(realMsg);
        }

        if (type == 0) {
            tv.setTextColor(Color.parseColor("#333333"));  //黑色
        } else if (type == 1) {
            tv.setTextColor(Color.parseColor("#008577"));  //绿色
        } else if (type == 2) {
            tv.setTextColor(Color.parseColor("#D81B60"));  //红色
        }

        tvLogInfo.addView(tv);

        if (tvLogInfo.getChildCount() > 1000) {
            tvLogInfo.removeViewAt(0);
        }

        //滚动到底部
        //需要将scrollview获取焦点
        svLogInfo.fullScroll(ScrollView.FOCUS_DOWN);

    }

    /**
     * 判断定位服务是否开启
     *
     * @param
     * @return true 表示开启
     */
    public boolean isLocationEnabled() {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }
}
